<template>
    <div id="inStocks">
        <!-- 面包导航 -->
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 搜索部分 -->
            <el-form size="small" :inline="true" :model="queryMap" class="demo-form-inline" >
                <el-form-item label="是否分期">
                    <el-select  clearable  v-model="queryMap.isperiodization" placeholder="请选择分期类型">
                        <el-option label="否" value="1"></el-option>
                        <el-option label="是" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="支付方式">
                    <el-select  clearable  v-model="queryMap.paymentmode" placeholder="请选择支付方式">
                        <el-option label="微信转账" value="1"></el-option>
                        <el-option label="支付宝转账" value="2"></el-option>
                        <el-option label="银行卡转账" value="3"></el-option>
                        <el-option label="现金支付" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="支付单号">

                    <el-input
                            clearable
                            @clear="search"
                            v-model="queryMap.paymentid"
                            placeholder="请输入入库单查询"
                            @keyup.enter.native="search"
                            class="input-with-select"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="学员姓名">
                  <!--  <el-select v-model="queryMap.studentid" placeholder="请选择学员">
                        <el-option
                                v-for="student in studentList"
                                :key="student.studentId"
                                :label="student.studentName"
                                :value="student.studentId"
                        ></el-option>
                    </el-select>-->
                    <el-autocomplete
                            value-key="name"
                            :clearable="true"
                            class="inline-input"
                            v-model="addForm.studentname"
                            :fetch-suggestions="querySearch"
                            placeholder="搜索学生名字"
                            @select="handleSelect" style="width: 288px"
                    ></el-autocomplete>
                </el-form-item>
                <el-form-item label="支付时间">
                    <el-date-picker
                            :clearable="false"
                            v-model="range"
                            type="datetimerange"
                            :value-format="'yyyy-MM-dd HH:mm:ss'"
                            :picker-options="pickerOptions"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-refresh" type="warning" @click="clearTime">重置</el-button>
                </el-form-item>


            </el-form>
            <div style="margin-bottom: 20px">
                <el-button type="success" icon="el-icon-plus" @click="toAdd">添加</el-button>
                <el-button type="button" icon="el-icon-download">导出</el-button>
            </div>

            <!-- 表格区域 -->
            <el-table size="mini" v-loading="loading" :data="tableData" border style="width: 100%;" height="420" :header-cell-style="tableHeaderStyle"
                      :cell-style="rowStyle">
                <el-table-column label="支付单号" prop="paymentid" width="100"></el-table-column>
                <el-table-column  prop="studentid" :show-overflow-tooltip='true' label="学员名称" width="80">
                    <template slot-scope="scope">
                        <span>{{scope.row.studentname}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="paymentmode" label="支付方式" width="100">
                    <template slot-scope="scope">
                        <el-tag  type="success" v-if="scope.row.paymentmode===1">微信转账</el-tag>
                        <el-tag  v-else-if="scope.row.paymentmode===2">支付宝转账</el-tag>
                        <el-tag  type="danger" v-else-if="scope.row.paymentmode===3">银行卡转账</el-tag>
                        <el-tag  type="warning" v-else>现金支付</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="paymentmoney" label="支付金额" sortable width="100"></el-table-column>
                <el-table-column label="支付时间" width="180">
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        <span style="margin-left: 10px">{{ scope.row.paymenttime }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="是否分期" width="100">
                    <template slot-scope="scope">
                        <el-tag size="mini" type="danger" effect="plain" v-if="scope.row.isperiodization==0">是</el-tag>
                        <el-tag size="mini" effect="plain" v-if="scope.row.isperiodization==1">否</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="preparedby" label="操作员" width="180"></el-table-column>
                <el-table-column label="备注" width="220">
                    <template slot-scope="scope">
                        <!-- 光标放在文字上面 悬出内容区域 -->
                        <el-popover trigger="hover" placement="top">
                            <p>备注: {{ scope.row.remarks }}</p>
                            <div slot="reference" class="name-wrapper">
                                <el-tag size="medium">{{ scope.row.remarks }}</el-tag>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" icon="el-icon-edit-outline" @click="edit(scope.row)"></el-button>
                        <el-button type="danger" size="small" icon="el-icon-delete" @click="del(scope.row.paymentid)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页部分 -->
            <el-pagination
                    style="margin-top:10px;"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>
            <!-- 缴费明细 -->
            <el-dialog title="入库明细" :visible.sync="dialogVisible" @close="closeDetail" width="60%">
                <!--                来源信息-->
                <el-card class="box-card" style="margin-bottom: 10px;">
                    <div  class="text item">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <div class="grid-content bg-purple">
                                    <span style="font-size: 11px;color: #303030;">省区市:</span> &nbsp;<el-tag size="mini" >{{supplier.address}}</el-tag>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="grid-content bg-purple">
                                    <span style="font-size: 11px;color: #303030;">具体位置:</span> &nbsp;<el-tag size="mini" >{{supplier.name}}</el-tag>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="grid-content bg-purple">
                                    <span style="font-size: 11px;color: #303030;">联系人 :</span> &nbsp;<el-tag size="mini"  >{{supplier.contact}}</el-tag>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="grid-content bg-purple">
                                    <span style="font-size: 11px;color: #303030;">电话 : </span>&nbsp;<el-tag size="mini" >{{supplier.phone}}</el-tag>
                                </div>
                            </el-col>

                        </el-row>
                    </div>
                </el-card>

                <!--                步骤条-->
                <el-steps simple v-if="pStatus==0"  style="margin-left: 10px;margin-bottom: 5px;" :space="200" :active="3" finish-status="success">
                    <el-step title="提交入库单" ></el-step>
                    <el-step title="审核入库单"></el-step>
                    <el-step title="进入库存"></el-step>
                </el-steps>
                <el-steps simple v-if="pStatus==2"  style="margin-left: 10px;margin-bottom: 5px;" :space="200" :active="2" finish-status="success">
                    <el-step title="提交入库单" ></el-step>
                    <el-step title="审核入库单"></el-step>
                    <el-step title="进入库存"></el-step>
                </el-steps>
                <span>
          <template>
            <el-table height="260" max-height="350" border :data="detailTable" style="width: 100%">
              <el-table-column prop="name" label="名称"></el-table-column>
              <el-table-column :show-overflow-tooltip="true" prop="pnum" label="商品编号"></el-table-column>
               <el-table-column prop="model" label="规格"></el-table-column>
              <el-table-column
                      prop="imageUrl"
                      label="图片"
                      align="center"
                      width="150px"
                      padding="0px"
              >
                <template slot-scope="scope">
                  <img
                          :src="'https://www.zykhome.club/'+scope.row.imageUrl"
                          alt
                          style="width: 30px;height:30px"
                  />
                </template>
              </el-table-column>
               <el-table-column prop="count" label="数量"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
            </el-table>
              <!--              明细分页-->
        <el-pagination
                style="margin-top:20px;"
                background
                @current-change="handleDetailSizeChange"
                :current-page="this.pageNum"
                :page-size="3"
                layout="prev, pager, next,total"
                :total="this.detailTotal">
        </el-pagination>
          </template>

        </span>
            </el-dialog>
            <!-- 添加和编辑对话框 -->
            <el-dialog :title="title" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
                <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="学生姓名" prop="studentname" required>
                        <el-autocomplete
                         value-key="name"
                        :clearable="true"
                        class="inline-input"
                        v-model="addForm.studentname"
                        :fetch-suggestions="querySearch"
                        placeholder="搜索学生名字"
                        @select="handleSelect" style="width: 288px"
                        ></el-autocomplete>
                    </el-form-item>
                    <el-form-item label="缴费金额" prop="paymentmoney" required>
                        <el-input-number v-model="addForm.paymentmoney" :precision="2" :step="0.1" :max="1000000000000000000000" style="width: 288px"></el-input-number>
                    </el-form-item>
                    <!--<el-form-item label="缴费模式" prop="region">
                        <el-select v-model="addForm.region" placeholder="请选择缴费模式">
                            <el-option label="a" value="a"></el-option>
                            <el-option label="a" value="a"></el-option>
                        </el-select>
                    </el-form-item>-->
                    <el-form-item label="支付时间" required>
                        <el-col :span="11">
                            <el-form-item prop="paymenttime">
                                <el-date-picker
                                        type="datetime"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        placeholder="选择日期"
                                        v-model="addForm.paymenttime"
                                        style="width: 100%"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="操作员">
                        <el-input v-model="addForm.preparedby" style="width: 288px"></el-input>
                    </el-form-item>
                    <el-form-item label="缴费项目">
                    <el-select v-model="addForm.pmtypeid" placeholder="请选择缴费项目">
                        <el-option
                                v-for="pmType in pmTypeList"
                                :key="pmType.pmtypeid"
                                :label="pmType.pmtypename"
                                :value="pmType.pmtypeid"
                        ></el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="是否分期" prop="isperiodization">
                        <el-radio-group v-model="addForm.isperiodization" size="medium">
                            <el-radio border  :label="0">是</el-radio>
                            <el-radio border :label="1">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="支付方式" prop="paymentmode" required>
                        <el-radio-group v-model="addForm.paymentmode">
                            <el-radio  :label="1">微信转账</el-radio>
                            <el-radio  :label="2">支付宝转账</el-radio>
                            <el-radio  :label="3">银行卡转账</el-radio>
                            <el-radio  :label="4">现金支付</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="备注" prop="desc">
                        <el-input type="textarea" v-model="addForm.remarks"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('addForm')">提交</el-button>
                        <el-button @click="resetForm('addForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: 'PayMent',

        data() { // 校验规则
            let validatorPrice = (rule, value, callback) => {
                    if (!value) return callback(new Error('请输入金额'))
                    if (!Number(value)) return callback(new Error('请输入数字值'))
                    // let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})$/g; //小数限制0-2位
                    let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
                    if (!reg.test(value)) return callback(new Error('请输入正确价格'));
                    callback();
                };
            var validatorName = (rule, value, callback) => {
                if (value) {
                    if (!value) {
                        callback(new Error("请输入学生姓名！"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("请输入学生姓名！"));
                }
            };
            return {
                title:"添加缴费信心",
                pickerOptions: {
                    shortcuts: [
                        {
                            text: '今天(此刻)',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '昨天',
                            onClick(picker) {
                                const end = new Date(new Date(new Date().toLocaleDateString()).getTime());
                                const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
                                start.setTime(start.getTime() - 3600 * 1000 * 24);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近一周',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近一个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                        }, {
                            text: '最近两个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 60);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近三个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                picker.$emit('pick', [start, end]);
                            }
                        }]
                },
                supplier:{},
                detailTotal:0,
                pageNum:1,
                detailId:undefined,
                loading: true,
                detailTable: [],
                pmTypeList:[],
                dialogVisible: false,
                total: 0,
                queryMap: {
                    pageNum: 1,
                    pageSize: 10,
                    paymentmode: '',
                    isperiodization:'',
                    paymentid:'',
                    studentid:''
                },
                tableData: [],
                range:[],
                pStatus:'',//步骤flag
                studentList:[],
                addDialogVisible:false,
                addForm:{},
                paymentmodeList:[],
                rules: {
                    studentname: [
                        { required: true, validator: validatorName, trigger: "change"},
                    ],
                    paymentmoney:[
                        {required: true, validator: validatorPrice, trigger: "blur"}
                    ],
                    paymenttime: [
                        { type: 'string', required: true, message: '请选择日期', trigger: 'change' }
                    ],

                    isperiodization: [
                        { required: true, message: '请选择分期', trigger: 'change' }
                    ],
                    paymentmode:[
                        {required: true, message: '请选择支付方式', trigger: 'change'}
                    ],
                    remarks: [
                        { required: true, message: '请填写备注', trigger: 'blur' }
                    ]
                },
                shcoolClass:[],
                queryStudList:[],
                timeout:null,
                tableHeaderStyle: { textAlign: "center" }, //表头居中
                getname:''
            };

        },
        methods: {
            //内容居中
            rowStyle() {
                return "text-align:center";
            },
            edit(row){
                this.title= "编辑缴费记录"
                this.addDialogVisible = true
                this.addForm = row
                this.getName(row.studentid)
                this.addForm.studentname = this.getname
            },
            querySearch(queryString, cb) {
                if(queryString!='') {//输入框中有值
                    this.findStuList(queryString, (data) => {
                        console.log(data);
                        var results = queryString ? data.filter(this.createStateFilter(queryString)) : data;
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(() => {
                            cb(results);
                        }, 5000*Math.random());
                    })
                }
            },
            findStuList(query,fun){
                if(query!='' && query !=null && query!= undefined){
                    let params = {
                        studentName:query
                    }
                    this.$http.post('/class/findStuList',params).then((res) =>{
                        this.queryStudList = res.data
                        this.shcoolClass = []
                        if(this.queryStudList.length>0){
                            this.queryStudList.forEach((item)=>{
                                this.shcoolClass.push({
                                    value:item.studentId,
                                    name:item.studentName
                                })
                            })
                        }else{
                            this.shcoolClass.push({
                                value:"未找到相关结果",
                                name:"未找到相关结果",
                            })
                        }
                        fun(this.shcoolClass);
                    })
                }

            },
            handleSelect(selected) {
                this.addForm.studentname = selected.name
                this.addForm.studentid = selected.value+''
            },
            createStateFilter(queryString) {
                return (item) => {
                    //item字段是全部所匹配到的大小写汉子
                    return (
                        item.name.toLowerCase().indexOf(queryString.toLowerCase())>-1
                    )
                }
            },
            /**
             * 关闭添加弹出框
             */
            closeDialog() {
                this.addForm = {};
            },
            submitForm(formName) {
                console.log(this.paymentmodeList);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(this.addForm)
                        if(this.addForm.paymentid){
                            this.updatePayMent()
                        }else{
                            this.savePayMent()
                        }
                    } else {
                        this.$message.error("必填项请认真填写，谢谢！")
                        return false;
                    }
                });
            },
            updatePayMent(){
                this.$http.put(
                    "/pay/update/" + this.addForm.paymentid,
                    this.addForm
                ).then((res)=>{
                    if(res.data.success){
                        this.$notify({
                            title: "操作成功",
                            message: "基本信息已更新",
                            type: "success"
                        });
                        this.loadTableData()
                        this.addDialogVisible = false
                    }else{
                        this.$message.error(res.data.data)
                    }
                })
            },
            savePayMent(){
                this.$http.post('/pay/add',this.addForm).then((res)=>{
                    if(res.data.success){
                        this.$notify({
                            title: "操作成功",
                            message: "基本信息添加成功",
                            type: "success"
                        });
                        this.loadTableData()
                        this.addDialogVisible = false
                    }else{
                        this.$message.error(res.data.data)
                    }
                })
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            toAdd(){
                this.addDialogVisible = true;
                this.addForm = {}
            },
            async getName(id){
                const { data: res } = await this.$http.get('/pay/getStuNameById/'+id);
                if(res.success){
                    this.getname = res.data.data
                }
                console.log(this.getname)
                return this.getname;
            },
            /**
             * 关闭明细
             */
            closeDetail(){
                this.pageNum=1;
            },
            clearTime(){
                this.queryMap= {pageNum: 1, pageSize: 10, paymentmode: '1',isperiodization:'1',paymentid:'',studentid:''};
                this.queryMap.startTime=null;
                this.queryMap.endTime=null;
                this.range=[];
            },
            /**
             *  改变页码
             */
            handleDetailSizeChange(newSize) {
                this.pageNum = newSize;
                this.detail(this.detailId);
            },

            /**删除明细
             */
            async del(paymentid) {
                const res = await this.$confirm(
                    "此操作将永久删除缴费记录, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
                if (res === "confirm") {
                    const {data: res} = await this.$http.delete("/pay/delete/" + paymentid);
                    if (!res.success) {
                        return this.$message.error("删除失败:" + res.data.errorMsg);
                    } else {
                        await this.loadTableData();
                        return this.$message.success("删除入库单记录成功");
                    }
                }
            },
            /**
             * 查看入库单明细
             */
            async detail(id) {
                this.detailId=id;
                const {data: res} = await this.$http.get("business/inStock/detail/" + id+"?pageNum="+this.pageNum);
                if (!res.success) {
                    this.$message.error("获取明细失败:" + res.data.errorMsg);
                } else {
                    this.detailTable = res.data.itemVOS;
                    this.detailTotal = res.data.total;
                    this.supplier=res.data.supplierVO;
                    this.pStatus=res.data.status;
                    this.dialogVisible = true;

                }

            },
            /**
             * 加载表格数据
             */
            async loadTableData() {

                if(this.range!=null&&this.range.length===1){
                    this.queryMap.startTime=this.range[0];
                }else if(this.range!=null&&this.range.length===2){
                    this.queryMap.startTime=this.range[0];
                    this.queryMap.endTime=this.range[1];
                }

                const {data: res} = await this.$http.get("/pay/findList", {
                    params: this.queryMap
                });
                if (!res.success) {
                    return this.$message.error("获取列表失败:"+res.data.errorMsg);
                } else {
                    this.total = res.data.total;
                    this.tableData = res.data.rows;
                    this.loading = false;
                }
            },
            /**
             * 改变页码
             */
            handleSizeChange(newSize) {
                this.queryMap.pageSize = newSize;
                this.loadTableData();
            },
            /**
             * 查询入库单
             */
            search() {
                this.queryMap.pageNum = 1;
                this.loadTableData();
            },
            /**
             * 点击分页
             */
            handleCurrentChange(current) {
                this.queryMap.pageNum = current;
                this.loadTableData();
            },
            getStudentList(){

            },
            /**
             * 加载所有部门
             */
            async getPayList() {
                const { data: res } = await this.$http.get("/payTpye/findAll");
                if(!res.success){
                    return this.$message.error("获取员工列表失败:"+res.data.errorMsg);
                }
                this.pmTypeList = res.data;
            },
        },
        created() {
            this.loadTableData();
            this.getPayList();
            // setTimeout(() => {
            //     this.loading = false;
            // }, 1000);
        }
    };
</script>


